package com.bailian.app.controller.Apis;

import com.bailian.common.annotation.Anonymous;
import com.bailian.app.controller.BaseAppController;
import com.bailian.common.core.domain.AjaxResult;
import com.bailian.system.domain.BlPhoneUser;
import com.bailian.system.service.IBlPhoneUserService;
import com.bailian.app.service.WechatMiniProgramService;
import com.bailian.framework.web.service.JwtTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信认证控制器
 * 
 * @author bailian
 */
@Api(tags = "微信认证相关接口")
@RestController
@RequestMapping("/app/api/auth")
public class WechatAuthController extends BaseAppController {

    @Autowired
    private WechatMiniProgramService wechatService;
    
    @Autowired
    private IBlPhoneUserService phoneUserService;
    
    @Autowired
    private JwtTokenService jwtTokenService;

    /**
     * 微信小程序登录
     */
    @Anonymous
    @ApiOperation("微信小程序登录")
    @PostMapping("/wx/login")
    public AjaxResult wxLogin(@RequestBody Map<String, Object> params) {
        try {
            String code = (String) params.get("code");
            String nickName = (String) params.get("nickName");
            String avatarUrl = (String) params.get("avatarUrl");
            String encryptedData = (String) params.get("encryptedData");
            String iv = (String) params.get("iv");
            if (code == null || code.isEmpty()) {
                return error("登录凭证不能为空");
            }
            if (encryptedData == null || iv == null) {
                return error("encryptedData参数不完整");
            }
            if (nickName == null || avatarUrl == null) {
                return error("nickName参数不完整");
            }
            // 调用微信登录服务
            Map<String, Object> result = wechatService.wxLogin(code, nickName, avatarUrl, encryptedData, iv);
            return success(result);
        } catch (Exception e) {
            return error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 解密微信手机号并绑定
     */
    @Anonymous
    @ApiOperation("解密微信手机号并绑定")
    @PostMapping("/wx/decryptPhone")
    public AjaxResult decryptPhone(@RequestBody Map<String, Object> params) {
        try {
            String encryptedData = (String) params.get("encryptedData");
            String iv = (String) params.get("iv");
            String sessionKey = (String) params.get("sessionKey");
            Long userId = Long.valueOf(params.get("userId").toString());
            
            if (encryptedData == null || iv == null || sessionKey == null || userId == null) {
                return error("参数不完整");
            }
            
            // 解密手机号
            String phoneNumber = wechatService.decryptPhoneNumber(encryptedData, iv, sessionKey);
            
            // 绑定手机号
            BlPhoneUser user = wechatService.bindPhoneNumber(userId, phoneNumber);
            
            return success(user);
        } catch (Exception e) {
            return error("手机号绑定失败：" + e.getMessage());
        }
    }
    
    /**
     * 微信小程序注册/绑定手机号（手动输入）
     */
    @Anonymous
    @ApiOperation("手动绑定手机号")
    @PostMapping("/wx/bindPhone")
    public AjaxResult bindPhone(@RequestBody BlPhoneUser phoneUser) {
        try {
            // 检查手机号是否已存在（通过查询列表方式）
            BlPhoneUser queryUser = new BlPhoneUser();
            queryUser.setPhone(phoneUser.getPhone());
            List<BlPhoneUser> existUsers = phoneUserService.selectBlPhoneUserList(queryUser);
            if (existUsers != null && !existUsers.isEmpty()) {
                return error("该手机号已被绑定");
            }
            
            // 保存用户信息
            phoneUser.setSource("微信小程序");
            int result = phoneUserService.insertBlPhoneUser(phoneUser);
            
            if (result > 0) {
                return AjaxResult.success("绑定成功", phoneUser);
            } else {
                return error("绑定失败");
            }
        } catch (Exception e) {
            return error("绑定失败：" + e.getMessage());
        }
    }

    /**
     * 刷新token
     */
    @ApiOperation("刷新token")
    @PostMapping("/wx/refreshToken")
    public AjaxResult refreshToken() {
        try {
            // 获取当前用户ID（拦截器已验证token）
            Long userId = getCurrentUserId();
            
            // 从请求头中获取token用于刷新
            String token = getCurrentRequest().getHeader("Authorization");
            
            if (token == null || token.isEmpty()) {
                return error("token不能为空");
            }
            
            // 如果token以"Bearer "开头，去掉前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            // 刷新token
            boolean refreshResult = wechatService.refreshToken(token);
            
            if (!refreshResult) {
                return error("token刷新失败");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token); // 返回原token，因为刷新只是延长有效期
            result.put("userId", userId);
            result.put("message", "token有效期已刷新");
            result.put("tokenType", "JWT");
            
            return AjaxResult.success("token刷新成功", result);
        } catch (Exception e) {
            logger.error("Token刷新失败", e);
            return error("token刷新失败：" + e.getMessage());
        }
    }
} 